/*
 *    Copyright (c) 2018-2025, haohanwork.com All rights reserved.
 */
package com.haohan.cloud.scm.opc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.constant.NumberPrefixConstant;
import com.haohan.cloud.scm.api.constant.enums.opc.YesNoEnum;
import com.haohan.cloud.scm.api.opc.entity.BuyerPayment;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.haohan.cloud.scm.opc.mapper.BuyerPaymentMapper;
import com.haohan.cloud.scm.opc.service.BuyerPaymentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * 采购商货款统计
 *
 * @author haohan
 * @date 2019-05-13 20:35:09
 */
@Service
@AllArgsConstructor
public class BuyerPaymentServiceImpl extends ServiceImpl<BuyerPaymentMapper, BuyerPayment> implements BuyerPaymentService {

    private final ScmIncrementUtil scmIncrementUtil;

    @Override
    public boolean save(BuyerPayment entity) {
        if (StrUtil.isEmpty(entity.getBuyerPaymentId())) {
            String sn = scmIncrementUtil.inrcSnByClass(BuyerPayment.class, NumberPrefixConstant.BUYER_PAYMENT_SN_PRE);
            entity.setBuyerPaymentId(sn);
        }
        return super.save(entity);
    }

    /**
     * 查询到期的账单数 (未结算)
     * @param endDate
     * @param buyerId
     * @param type   状态 是否结算 0否1是  null默认否
     * @return
     */
    @Override
    public int countBill(LocalDate endDate, String buyerId, YesNoEnum type) {
        type = (null == type) ? YesNoEnum.no : type;
        QueryWrapper<BuyerPayment> query = new QueryWrapper<>();
        query.lambda()
                .eq(BuyerPayment::getBuyerId, buyerId)
                .eq(BuyerPayment::getStatus, type)
                .le(BuyerPayment::getBuyDate, endDate);
        return super.count(query);
    }

    /**
     * 根据 编号查询
     * @param payment 可传pmId
     * @return
     */
    @Override
    public BuyerPayment fetchBySn(BuyerPayment payment) {
        QueryWrapper<BuyerPayment> query = new QueryWrapper<>();
        query.lambda()
                .eq(BuyerPayment::getBuyerPaymentId, payment.getBuyerPaymentId())
                .eq(StrUtil.isNotBlank(payment.getPmId()), BuyerPayment::getPmId, payment.getPmId());
        return super.getOne(query);
    }
}
